package com.hqhsc.module.manage.activity.controller;

import com.hqhsc.module.common.service.CommonService;
import com.hqhsc.module.common.service.FileService;
import com.hqhsc.module.init.service.InitService;
import com.hqhsc.module.login.domain.User;
import com.hqhsc.module.manage.activity.domain.Activity;
import com.hqhsc.module.manage.activity.domain.ActivityChannelDetail;
import com.hqhsc.module.manage.activity.domain.ActivityTemplet;
import com.hqhsc.module.manage.activity.service.ActivityManageService;
import com.hqhsc.module.manage.activityuser.domain.ActivityUser;
import com.hqhsc.module.manage.activityuser.service.ActivityUserManageService;
import com.hqhsc.module.manage.channel.domain.Channel;
import com.hqhsc.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

@Controller
@RequestMapping("/manage/activity")
public class ActivityManageController {
	final Logger logger = LoggerFactory.getLogger(ActivityManageController.class);

	@Autowired
	private CommonService commonService;
    @Autowired
    private ActivityManageService activityManageService;
    @Autowired
    private FileService fileService;
	@Autowired
	private Properties appProps;


    /**
     * 活动管理-首页
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/index" , method = {RequestMethod.GET , RequestMethod.POST})
    public String index(Model model , HttpServletRequest request , HttpServletResponse response) {
        User user = (User)request.getSession().getAttribute("user");

        String pageindexStr = request.getParameter("page_index");//第几页
        int page_index = Integer.parseInt(StringUtils.isBlank(pageindexStr) || "0".equals(pageindexStr) ? "1" : pageindexStr);
        int size = Integer.valueOf(appProps.get("manage.activity.index.size").toString());//每页显示条数
        int start = (page_index - 1) * size;

        String activity_name = request.getParameter("activity_name");

        String method = request.getMethod();
        if("GET".equals(method.toUpperCase()) && StringUtils.isNotEmpty(activity_name)) {//get请求，进行编码格式转换
            activity_name = this.commonService.characterFormat(activity_name , "ISO8859-1" , "UTF-8");
        }

        String activity_type = request.getParameter("activity_type");
        int activity_type_int = -1;
        if(StringUtils.isNotEmpty(activity_type)) {
            activity_type_int = Integer.valueOf(activity_type);
        }
        String orderby = request.getParameter("orderby");

        logger.info("manage activity index page_index:"+page_index+",activity_name:"+activity_name+",activity_type:"+activity_type+",orderby:"+orderby);

        Map<String , Object> map = this.activityManageService.getActivityList(0, activity_name,activity_type_int , orderby , start, size);
        long total = Long.valueOf(map.get("total").toString());
        List<Activity> activity_list = (List<Activity>)map.get("activity_list");

        long temp = (total - 1) <= 0 ? 0 : (total - 1);
        int pages = Integer.parseInt(Long.toString(temp / size)) + 1;
        int prepages = (page_index - 1) <= 0 ? 1 : (page_index - 1);
        int nextpages = (page_index + 1) >= pages ? pages : (page_index + 1);

        model.addAttribute("current_page" , page_index);
        model.addAttribute("pages" , pages);
        model.addAttribute("prepage" , prepages);
        model.addAttribute("nextpage" , nextpages);
        model.addAttribute("page_url" , request.getRequestURI());

        String condition = "";
        if(StringUtils.isNotEmpty(activity_name)) {
            condition = condition + "&activity_name="+activity_name;
        }
        if(StringUtils.isNotEmpty(orderby)) {
            condition = condition + "&orderby="+orderby;
        }
        if(StringUtils.isNotEmpty(activity_type)) {
            condition = condition + "&activity_type="+activity_type;
        }
        model.addAttribute("condition" , condition);

        model.addAttribute("activity_name" , activity_name);
        model.addAttribute("orderby" , orderby);
        model.addAttribute("activity_type" , activity_type);
        model.addAttribute("activity_list" , activity_list);
        return "/module/manage/activity/index";
    }

    /**
     * 新增活动，首选需要选择活动模板
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/choosetemp" , method = RequestMethod.GET)
    public String chooseTemp(Model model , HttpServletRequest request , HttpServletResponse response) {
        User user = (User)request.getSession().getAttribute("user");

        String pageindexStr = request.getParameter("page_index");//第几页
        int page_index = Integer.parseInt(StringUtils.isBlank(pageindexStr) || "0".equals(pageindexStr) ? "1" : pageindexStr);
        int size = Integer.valueOf(appProps.get("manage.activity.choosetemp.size").toString());//每页显示条数
        int start = (page_index - 1) * size;

        Map<String , Object> map = this.activityManageService.getActivityTempletList(start, size);
        long total = Long.valueOf(map.get("total").toString());
        List<ActivityTemplet> activityTempletList = (List<ActivityTemplet>)map.get("activity_templet_list");

        long temp = (total - 1) <= 0 ? 0 : (total - 1);
        int pages = Integer.parseInt(Long.toString(temp / size)) + 1;
        int prepages = (page_index - 1) <= 0 ? 1 : (page_index - 1);
        int nextpages = (page_index + 1) >= pages ? pages : (page_index + 1);

        model.addAttribute("current_page" , page_index);
        model.addAttribute("pages" , pages);
        model.addAttribute("prepage" , prepages);
        model.addAttribute("nextpage" , nextpages);
        model.addAttribute("page_url" , request.getRequestURI());

        model.addAttribute("activity_templet_list" , activityTempletList);

        return "/module/manage/activity/choosetemp";
    }

    /**
     * 选择完模板后，跳转到新增活动页面
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/add" , method = RequestMethod.GET)
    public String addActivity(Model model , HttpServletRequest request , HttpServletResponse response) {
        User user = (User)request.getSession().getAttribute("user");

        String templet_id_str = request.getParameter("templet_id");
        int templet_id = StringUtils.isEmpty(templet_id_str) ? 0 : Integer.valueOf(templet_id_str);

        List<Channel> channel_list = this.activityManageService.getChannelList();

        model.addAttribute("channel_list" , channel_list);
        model.addAttribute("templet_id" , templet_id);
        return "/module/manage/activity/add";
    }


    @RequestMapping(value = "/doadd" , method = RequestMethod.POST)
    public String doAddActivity(Model model , HttpServletRequest request , HttpServletResponse response , @RequestParam("file_upload") CommonsMultipartFile file_upload) {
        User user = (User)request.getSession().getAttribute("user");

        String activity_name = request.getParameter("activity_name");
        String templet_id = request.getParameter("templet_id");
        String type = request.getParameter("activity_type");
        String title = request.getParameter("title");
        String desc = request.getParameter("desc");
        String content = request.getParameter("activity_content");
        String flow = request.getParameter("flow");//aaa,bbb,ccc,ddd
        String place = request.getParameter("address");
        String begin_time = request.getParameter("begin_time");
        String end_time = request.getParameter("end_time");
        String[] channel_ids_arg = request.getParameterValues("channel_ids");

        this.activityManageService.doAddActivity(activity_name, Integer.valueOf(templet_id), Integer.valueOf(type), title, desc, content, flow, place, begin_time, end_time,channel_ids_arg , request , file_upload , user.getUser_id());
        return "redirect:/manage/activity/index";
    }

    @RequestMapping(value = "/detail" , method = RequestMethod.GET)
    public String activityDetail(Model model , HttpServletRequest request , HttpServletResponse response) {
        User user = (User)request.getSession().getAttribute("user");

        String activity_id = request.getParameter("aid");

        Activity activity_info = this.commonService.getSysActivityById(Long.valueOf(activity_id));
        activity_info.setBegin_time(activity_info.getBegin_time().substring(0 , activity_info.getBegin_time().length()-2));
        activity_info.setEnd_time(activity_info.getEnd_time().substring(0 , activity_info.getEnd_time().length()-2));
        activity_info.setCreate_at(activity_info.getCreate_at().substring(0 , activity_info.getCreate_at().length()-2));

        String qr_code_url = appProps.get("base.url") + "hqhsc/activity/signup/normal";
        List<ActivityChannelDetail> activity_channel_detail_list = this.activityManageService.getActivityChannelDetail(request , Long.valueOf(activity_id) , activity_info.getName() , qr_code_url);

        model.addAttribute("activity_info" , activity_info);
        model.addAttribute("activity_channel_detail_list" , activity_channel_detail_list);

        return "/module/manage/activity/detail";
    }

    @RequestMapping(value = "/export" , method = RequestMethod.GET)
    public void exportChannel(Model model , HttpServletRequest request , HttpServletResponse response) throws IOException {
        User user = (User)request.getSession().getAttribute("user");

        String activity_ids = request.getParameter("activity_ids");
        List<Activity> activity_list = this.activityManageService.getActivityListByIds(activity_ids);

        String base_path = request.getSession().getServletContext().getRealPath("/");
        String file_path = appProps.getProperty("activity.download.realpath");
        String file_name = "活动合集";
        if(activity_list.size() <= 1) {
            file_name = activity_list.get(0).getName();
        }

        String path = base_path + file_path + file_name + "-" + DateUtil.getDate(new Date(), "yyyy-MM-dd") +".xls";
        this.fileService.writeActivityExcel(activity_list , path);

        this.fileService.exportFile(response , new File(path) , false);
    }

    @RequestMapping(value = "/edit" , method = RequestMethod.GET)
    public String editActivity(Model model , HttpServletRequest request , HttpServletResponse response) {
        User user = (User)request.getSession().getAttribute("user");

        String activity_id = request.getParameter("aid");
        Activity activity_info = this.commonService.getSysActivityById(Long.valueOf(activity_id));

        List<ActivityChannelDetail> activityChannelDetailList = this.activityManageService.getActivityChannelDetail(Long.valueOf(activity_id));
        List<Channel> channel_list = this.activityManageService.getChannelList();

        for(Channel channel : channel_list) {
            for(ActivityChannelDetail acd : activityChannelDetailList) {
                if(channel.getId() == acd.getChannel_id()) {
                    channel.setIs_choose(1);
                    break;
                }
            }
        }

        model.addAttribute("channel_list" , channel_list);
        model.addAttribute("activity_info" , activity_info);
        return "/module/manage/activity/edit";
    }

    @RequestMapping(value = "/doedit" , method = RequestMethod.POST)
    public String channelDoEdit(Model model , HttpServletRequest request , HttpServletResponse response) {
        User user = (User)request.getSession().getAttribute("user");

        String activity_name = request.getParameter("activity_name");
        String type = request.getParameter("activity_type");
        String title = request.getParameter("title");
        String desc = request.getParameter("desc");
        String content = request.getParameter("activity_content");
        String flow = request.getParameter("flow");//aaa,bbb,ccc,ddd
        String place = request.getParameter("address");
        String begin_time = request.getParameter("begin_time");
        String end_time = request.getParameter("end_time");
        String[] channel_ids_arg = request.getParameterValues("channel_ids");
        String activity_id = request.getParameter("activity_id");
        this.activityManageService.activityDoEdit(Long.valueOf(activity_id) ,activity_name , Integer.valueOf(type), title, desc, content, flow, place, begin_time, end_time,channel_ids_arg , user.getUser_id());

        return "redirect:/manage/activity/detail?aid="+activity_id;
    }

    /**
     * 下线，即把status，从1更新成0
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/downline" , method = RequestMethod.GET)
    public String downline(Model model , HttpServletRequest request , HttpServletResponse response) {
        User user = (User)request.getSession().getAttribute("user");

        String activity_id = request.getParameter("aid");
        logger.info("manage activity downline aid:"+activity_id);
        this.activityManageService.updateStatus(Long.valueOf(activity_id) , 0 , user.getUser_id());
        return "redirect:/manage/activity/detail?aid="+activity_id;
    }

    /**
     * 上线，即把status，从0更新成1
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/upline" , method = RequestMethod.GET)
    public String upline(Model model , HttpServletRequest request , HttpServletResponse response) {
        User user = (User)request.getSession().getAttribute("user");

        String activity_id = request.getParameter("aid");
        logger.info("manage activity upline aid:"+activity_id);
        this.activityManageService.updateStatus(Long.valueOf(activity_id) , 1 , user.getUser_id());
        return "redirect:/manage/activity/detail?aid="+activity_id;
    }

}